#include "laurin-device.h"
#include <linux/sockios.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <string.h>  //form strncpy

LaurinDevice::LaurinDevice(const Glib::ustring& iface)
{
	_ifaceName = Glib::ustring(iface);

	// if not present, return 0
	_ifaceIndex = if_nametoindex(_ifaceName.c_str());

}


LaurinDevice::~LaurinDevice(){}


bool LaurinDevice::setDeviceUp()
{
	if(!isDeviceUp())
		return setDeviceStatus(1);

	return true;
}


bool LaurinDevice::setDeviceDown()
{
	if(isDeviceUp())
		return setDeviceStatus(0);

	return true;
}


bool LaurinDevice::isDeviceUp()
{
	//TODO error handling

    struct ifreq ifr;
    int sock;

    if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
    	return false;

    strncpy (ifr.ifr_name, _ifaceName.c_str(), IFNAMSIZ);

    bool ret = true;
    if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0)
        ret = false;
    else
    	ret = (ifr.ifr_flags & IFF_UP);

    close(sock);

    return ret;
}


bool LaurinDevice::setDeviceStatus(short flag)
{
	//TODO: error handling

	int sock;
	struct ifreq ifr;

	if((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
		return false;

	strncpy (ifr.ifr_name, _ifaceName.c_str(), IFNAMSIZ);

	if(flag)
		ifr.ifr_flags |= IFF_UP;
	else
		ifr.ifr_flags &= ~IFF_UP;

	bool ret = true;
	if(ioctl(sock, SIOCSIFFLAGS, &ifr) < 0)
		ret = false;

	close(sock);

	return ret;
}


int LaurinDevice::getDeviceIndex() const
{
	return _ifaceIndex;
}


Glib::ustring LaurinDevice::getDeviceName() const
{
	return _ifaceName;
}
